package com.atjava.webspider.logic;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.atjava.webspider.consts.Const;
import com.atjava.webspider.model.Output;
import com.atjava.webspider.model.Page;
import com.atjava.webspider.model.Site;
import com.atjava.webspider.model.Variable;
import com.atjava.webspider.util.DateUtil;
import com.atjava.webspider.util.FileSystemUtil;
import com.atjava.webspider.util.HttpUtil;
import com.atjava.webspider.util.LogUtil;
import com.atjava.webspider.util.RegexpUtil;
import com.atjava.webspider.util.XmlUtil;

public class VarLogic {
	
	private Output output;
	private Page page;
	
	public VarLogic(Output output,Page page){
		this.output = output;
		this.page = page;
	}

	public static String getVarExp(String key){
		
		return "#{" + key + "}#";
	}
	
	public static String getListVarExp(String key,int n){
		
		return "#{" + key + "[" + n + "]}#";
	}
	
	public static String getIterateStartExp(String key){
		
		return "#{" + key + "-start}#";
	}
	
	public static String getIterateEndExp(String key){
		
		return "#{" + key + "-end}#";
	}
	
	public static String [] getAvailableVarHeader(int n){
		String[] header = new String[n];
		for (int i = 1; i <= header.length; i++) {
			header[i-1] = "变量" + i;
		}
		return header;
	}
	
	public static String getRepeat(String s ,String key){
		String startExp = getIterateStartExp(key);
		String endExp = getIterateEndExp(key);
		int startIdx = s.indexOf(startExp);
		int endIdx = s.indexOf(endExp);
		if(startIdx < 0 || endIdx < 0)
			return "";
		return s.substring(startIdx + startExp.length(),endIdx);
	}
	
	public String systemVars(URL url,String text){
		//url
		text = RegexpUtil.replaceAll(text, VarLogic.getVarExp("url"), url.toString());
		//所属网站
		text = RegexpUtil.replaceAll(text, VarLogic.getVarExp("site"), HttpUtil.getHost(url.toString()));
		//系统日期
		text = RegexpUtil.replaceAll(text, VarLogic.getVarExp("sysdate"), DateUtil.formatDataCN(new Date()));
		
		return text;
	}
	public String systemVarsXml(URL url){
		StringBuffer xml = new StringBuffer();
		//url
		xml.append("<url>");xml.append(url.toString());xml.append("</url>\r\n");
		//host
		xml.append("<site>");
		xml.append(HttpUtil.getHost(url.toString()));
		xml.append("</site>\r\n");
		//sysdate
		xml.append("<sysdate>");
		xml.append(DateUtil.formatDataCN(new Date()));
		xml.append("</sysdate>\r\n");
		return xml.toString();
	}
	
	public String userVars(URL url, String content, String template, VarPrcsor prcsor){
		//自定义变量
		List<Variable> variables = page.getVariables();
		if(variables == null)
			return template;
		for (int i = 0; i < variables.size(); i++) {
			Variable var = variables.get(i);
			//变量名#{name}#
			String key = VarLogic.getVarExp(var.getName());
			//变量取值规则
			String regexp = RegexpUtil.replaceBlank(var.getRegexp());
			//变量值集合
			List<String> values = RegexpUtil.getGroupList(content, regexp, var.getGroupNum());
			//获得重复内容
			String inRepeat = VarLogic.getRepeat(template, var.getName());
			if(StringUtils.isNotBlank(inRepeat)){
				StringBuffer repeats = new StringBuffer();
				for (int j = 0; j < values.size(); j++) {
					repeats.append(inRepeat.replace(key, values.get(j)));
				}
				String repeatUnit = getIterateStartExp(var.getName()) + inRepeat + getIterateEndExp(var.getName());
				String replacedRepeats = prcsor.processValue(url,content,repeats.toString(),output);
				template = template.replace(repeatUnit, replacedRepeats);
			}
			//不重复
			if( values.size() > 0){
				String value = prcsor.processValue(url,content,values.get(0),output);
				template = RegexpUtil.replaceAll(template, key, value);
			}
		}
		return template;
	}
	
	public static Set<String> getVarNamesFromFolder(String folder){
		Set<String> varSet = new HashSet<String>();
		//从指定文件夹中获得各站点的样例数据文件 
		Map<String, File> sampleFileMap = getSampleFiles(folder);
		Iterator<String> siteIter = sampleFileMap.keySet().iterator();
		while(siteIter.hasNext()){
			//站点名称
			String siteName = siteIter.next();
			//站点对象
			Site site = (Site)CommonLogic.getByName
				(ConfigLogic.getSiteConfig().getSites(), siteName);
			//站点样式文件
			File sampleFile = sampleFileMap.get(siteName);
			try {
				//样式文件变量
				Map<String, String> sampleVarMap = XmlUtil.readVarMap(sampleFile, site.getCharset());
				if(varSet.size() == 0)
					varSet.addAll(sampleVarMap.keySet());
				else
					varSet = CommonLogic.getCrossElements(varSet, sampleVarMap.keySet());
			} catch (Exception e) {
				LogUtil.info("从文件 [ " + sampleFile.getAbsolutePath() + " ] 中读取变量失败！");
				e.printStackTrace();
			}
		}
		return varSet;
	}
	
	public static int getVarCountFromFolder(String folder){
		int count = 0;
		List<File> dataFiles = FileSystemUtil.getFilesList(new File(folder), "xml");
		for (int i = 0; i < dataFiles.size(); i++) {
			File xmlFile = dataFiles.get(i);
			if(XmlUtil.isDataFile(xmlFile))
				count++;
		}
		return count;
	}
	
	public static Map<String, File> getSampleFiles(String folder){
		List<File> dataFiles = FileSystemUtil.getFilesList(new File(folder), "xml");
		Map<String, File> sampleFileMap = new HashMap<String, File>();
		for (int i = 0; i < dataFiles.size(); i++) {
			File xmlFile = dataFiles.get(i);
			if(!XmlUtil.isDataFile(xmlFile))
				continue;
			//if(xmlFile.getName().indexOf(Const.DATA_NAME_SEPARATOR) <= 0)
				//continue;
			String site = xmlFile.getName().split(Const.DATA_NAME_SEPARATOR)[0];
			//站点样式数据文件列表，如果没有则加入
			if(!sampleFileMap.keySet().contains(site))
				sampleFileMap.put(site, xmlFile);
		}
		return sampleFileMap;
	}
}
